package com.zsc.shixun.service.function.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zsc.shixun.contant.Contant;
import com.zsc.shixun.entity.Menu;
import com.zsc.shixun.entity.Role;
import com.zsc.shixun.entity.RoleAuthority;
import com.zsc.shixun.mapper.RoleMapper;
import com.zsc.shixun.model.authority.*;
import com.zsc.shixun.service.IMenuService;
import com.zsc.shixun.service.IRoleAuthorityService;
import com.zsc.shixun.service.IRoleService;
import com.zsc.shixun.service.IUserService;
import com.zsc.shixun.service.function.AuthorityService;
import com.zsc.shixun.utils.LoginMessageUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * <p>
 * 权限管理
 * </p>
 *
 * @author ZWYZY
 * @since 2020/6/22
 */
@Service
public class AuthorityServiceImpl implements AuthorityService {
    private static final Logger logger = LoggerFactory.getLogger(AuthorityServiceImpl.class);

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private IRoleService roleService;
    @Autowired
    private IRoleAuthorityService roleAuthorityService;

    @Autowired
    private IMenuService menuService;

    @Autowired
    private RoleMapping roleMapping;

    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private LoginMessageUtils loginMessageUtils;

    @Autowired
    private IUserService userService;

    @Override
    public List<RoleVO> getRole() {
        List<RoleVO> roleVOS = roleMapping.entitysToVos(roleService.list());
        return roleVOS;
    }

    @Override
    public void insert(AuthorityCreateVO authorityCreateVO) {
        Role role = new Role();
        BeanUtils.copyProperties(authorityCreateVO.getRoleCreateVO(), role);
        roleMapper.insert(role);
        System.out.println("---------------------角色id------------------");
        System.out.println(role.getId());
        logger.info("创建角色成功");
        for (PermissionVO permissionVO : authorityCreateVO.getPermissionVOList()
        ) {
            //判断菜单项权限列表长度是否为0，是则继续操作，否则不执行
            if (permissionVO.getAuthVOList().size() != 0) {
                RoleAuthority roleAuthority = new RoleAuthority();
                roleAuthority.setRoleId(role.getId());
                roleAuthority.setMenuId(permissionVO.getId());
                List<String> authValueList = new ArrayList<>(10);
                permissionVO.getAuthVOList().forEach(authVO ->
                        authValueList.add(authVO.getAuthValue())
                );
//                for (AuthVO authVO : permissionVO.getAuthVOList()
//                ) {
//                    authValueList.add(authVO.getAuthValue());
//                }
                roleAuthority.setAuthValue(StringUtils.join(authValueList, ","));
                String value = StringUtils.join(authValueList, ",");
                System.out.println("------------拼接后的字符串--------------");
                System.out.println(value);
                //插入
                roleAuthorityService.save(roleAuthority);
                logger.info("插入角色权限成功");
            }


        }
    }

    @Override
    public void delete(Long id) {
        roleService.removeById(id);
        logger.info("删除角色成功");
    }

    @Override
    public AuthorityVO getAuthority() {
        if (redisTemplate.hasKey(Contant.MENU_AUTHORITY_KEY)) {
            return (AuthorityVO) redisTemplate.opsForValue().get(Contant.MENU_AUTHORITY_KEY);
        }
        AuthorityVO authorityVO = new AuthorityVO();
        List<PermissionVO> permissionVOList = new ArrayList<>(10);
        List<Menu> menus = menuService.list();
        for (Menu m : menus
        ) {
            PermissionVO permissionVO = new PermissionVO();
            permissionVO.setMenuName(m.getName());
            permissionVO.setId(m.getId());
            String[] authNameArray = m.getAuthName().split(",");
            String[] authValueArray = m.getAuthValue().split(",");
            List<AuthVO> authVOS = new ArrayList<>(10);
            for (int i = 0; i < authNameArray.length; i++) {
                AuthVO authVO = new AuthVO();
                authVO.setAuthName(authNameArray[i]);
                authVO.setAuthValue(authValueArray[i]);
                authVOS.add(authVO);
            }
            permissionVO.setAuthVOList(authVOS);
            permissionVOList.add(permissionVO);
        }
        authorityVO.setPermissionVOList(permissionVOList);
        redisTemplate.opsForValue().set(Contant.MENU_AUTHORITY_KEY, authorityVO);
        System.out.println("-------权限列表----------");
        System.out.println(authorityVO);
        return authorityVO;
    }


    @Override
    public List<String> getPrivateAuthority(Long id) {
        List<RoleAuthority> roleAuthorityList = roleAuthorityService.list(new QueryWrapper<RoleAuthority>().lambda().eq(RoleAuthority::getRoleId, id));
        List<String> list = new ArrayList<>(10);
        roleAuthorityList.forEach(roleAuthority -> list.addAll(Arrays.asList(roleAuthority.getAuthValue().split(","))));
//        for (RoleAuthority roleAuthority : roleAuthorityList
//        ) {
//            list.addAll(Arrays.asList(roleAuthority.getAuthValue().split(",")));
//        }
        return list;
    }

    @Override
    public void update(AuthorityUpdateVO authorityUpdateVO) {
        Role role = new Role();
        BeanUtils.copyProperties(authorityUpdateVO.getRoleUpdateVO(), role);
        //修改角色
        roleService.updateById(role);
        logger.info("修改角色成功");
        //角色id
        Long roleId = role.getId();
        //遍历所有菜单项及权限
        for (PermissionVO permissionVO : authorityUpdateVO.getPermissionVOList()
        ) {
            //条件构造器
            LambdaQueryWrapper<RoleAuthority> roleAuthorityLambdaQueryWrapper = new QueryWrapper<RoleAuthority>().lambda().eq(RoleAuthority::getRoleId, role.getId()).eq(RoleAuthority::getMenuId, permissionVO.getId());
            //菜单项权限列表判断长度是否为0
            if (permissionVO.getAuthVOList().size() != 0) {
                RoleAuthority roleAuthority = new RoleAuthority();
                roleAuthority.setRoleId(role.getId());
                roleAuthority.setMenuId(permissionVO.getId());
                List<String> authValueList = new ArrayList<>(10);
                permissionVO.getAuthVOList().forEach(authVO -> authValueList.add(authVO.getAuthValue()));
//                for (AuthVO authVO : permissionVO.getAuthVOList()
//                ) {
//                    authValueList.add(authVO.getAuthValue());
//                }
                roleAuthority.setAuthValue(StringUtils.join(authValueList, ","));
                String value = StringUtils.join(authValueList, ",");
                System.out.println("------------拼接后的字符串--------------");
                System.out.println(value);
                //判断角色是否已有该菜单项至少一个权限
                if (roleAuthorityService.getOne(roleAuthorityLambdaQueryWrapper) != null) {
                    roleAuthorityService.update(roleAuthority, roleAuthorityLambdaQueryWrapper);
                } else {
                    roleAuthorityService.save(roleAuthority);
                }
                logger.info("修改角色权限成功");
            } else {
                if (roleAuthorityService.getOne(roleAuthorityLambdaQueryWrapper) != null) {
                    roleAuthorityService.remove(roleAuthorityLambdaQueryWrapper);
                }
            }
        }
        //判断修改的角色是否是当前登录在线的角色，是则清空缓存更改登录信息
        if (roleId.equals(loginMessageUtils.getMessage().getLoginUser().getRoleId())) {
            userService.updateUserCache(loginMessageUtils.getMessage().getLoginUser().getId());
        }
    }
}
